<input id="positions-save" type="button" value="Sačuvaj novi redolsed" onclick="updatePositions()" style="display:none">

<h1>Početna strana</h1>
<p class="actions"><?= $this->Html->link('+Nova stavka', '/admin_home/create', array(
    'class' => 'add',
    'title' => 'Nova stavka'
)) ?></p>
<ul class="sortable" id="home-items">
    <? foreach ($homeItems as $item): ?>
    <? $item = $item['HomeItem'] ?>
    <li value="<?= $item['id'] ?>">
        <h2><?= $item['title'] ?></h2>
        <?= $this->Html->image('home_items/'.$item['image'].'?h=100') ?>
        <?= $item['blurb'] ?>
        
        <div class="actions">
            <?= $this->Html->link('', '/admin_home/edit/'.$item['id'], array(
                'class' => 'edit',
                'title' => 'Izmeni'
            )) ?>
            <?= $this->Html->link('', '/admin_home/remove/'.$item['id'], array(
                'confirm' => 'Da li želite da obrišete stavku?',
                'class'   => 'delete',
                'title'   => 'Obriši'
            )) ?>
        </div> 
    </li>
    <? endforeach ?>
</ul>

<script type="text/javascript">
$(function(){
    $('#home-items').sortable({
        revert: 'invalid',
        forcePlaceholderSize: true,
        placeholder: 'placeholder',
        stop: function() {
            $('#positions-save').show()
        }
    })
})

function updatePositions() {
    var btn = $('#positions-save');
    if (btn.hasClass('loading')) {
        return
    }
    
    var positions = [];
    $('#home-items li').each(function(index){
        positions.push({
            id:       $(this).attr('value'),
            position: index
        })
    });
    
    $.ajax({
        url: '/admin_home/save_positions',
        type: 'post',
        data: {data: positions},
        beforeSend: function() {
            btn.addClass('loading');
        },
        complete: function(req) {
            btn.removeClass('loading');
            
            alert(req.responseText);
            if (req.status == 200) {
                btn.hide();
            }
        }
    })
}
</script>